package com.sky.service.impl;

import com.sky.dto.GoodsSalesDTO;
import com.sky.entity.Orders;
import com.sky.mapper.OrdersDetailMapper;
import com.sky.mapper.OrdersMapper;
import com.sky.mapper.UserMapper;
import com.sky.service.ReportService;
import com.sky.service.WorkSpaceService;
import com.sky.vo.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.annotations.Select;
import org.apache.poi.util.StringUtil;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Service
public class ReportServiceImpl implements ReportService {

    @Autowired
    private OrdersMapper ordersMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private OrdersDetailMapper ordersDetailMapper;
    @Autowired
    private WorkSpaceService workSpaceService;


    @Override
    public TurnoverReportVO turnoverStatistics(LocalDate begin, LocalDate end) {

        List<LocalDate> dateList = new ArrayList();
        dateList.add(begin);
        while (!begin.equals(end)){
            begin = begin.plusDays(1);
            dateList.add(begin);
        }

        List<Double> turnoverList = new ArrayList<>();
        dateList.forEach(date->{
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);

            Map map = new HashMap<>();
            map.put("begintime", begintime);
            map.put("endtime", endtime);
            map.put("status",Orders.COMPLETED);
            Double turnover = ordersMapper.getturnover(map);
            turnover = turnover == null?0:turnover;
            turnoverList.add(turnover);
        });

        return TurnoverReportVO
                .builder()
                .dateList(StringUtils.join(dateList, ","))
                .turnoverList(StringUtils.join(turnoverList, ","))
                .build();
    }

    @Override
    public UserReportVO userStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> datelist = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }

        List<Integer> newUserList = new ArrayList<>();
        List<Integer> totalUserList = new ArrayList<>();
        datelist.forEach(date->{
           LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
           LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            Integer nnmberNewUsers = userMapper.getNnmberNewUsers(begintime, endtime);
            nnmberNewUsers = nnmberNewUsers == null?0:nnmberNewUsers;
            newUserList.add(nnmberNewUsers);
            Integer nnmberTotalUser = userMapper.getNnmberTotalUser(begintime, endtime);
            nnmberTotalUser = nnmberTotalUser == null?0:nnmberNewUsers;
            totalUserList.add(nnmberTotalUser);
        });

        return UserReportVO
                .builder()
                .dateList(StringUtils.join(datelist, ","))
                .newUserList(StringUtils.join(newUserList, ","))
                .totalUserList(StringUtils.join(totalUserList, ","))
                .build();



    }

    @Override
    public OrderReportVO ordersStatistics(LocalDate begin, LocalDate end) {
        ArrayList<LocalDate> datelist = new ArrayList<>();
        while (!begin.equals(end)) {
            begin = begin.plusDays(1);
            datelist.add(begin);
        }
        List<Integer> orderCountList = new ArrayList<>();
        List<Integer> validOrderCountList = new ArrayList<>();
        datelist.forEach(date->{
            LocalDateTime begintime = LocalDateTime.of(date, LocalTime.MIN);
            LocalDateTime endtime = LocalDateTime.of(date, LocalTime.MAX);
            HashMap map = new HashMap<>();
            map.put("begintime", begintime);
            map.put("endtime", endtime);
            Integer getOrderCountList = ordersMapper.getNumberByStatusAndTime(map);
            getOrderCountList = getOrderCountList == null?0:getOrderCountList;

            orderCountList.add(getOrderCountList);
            map.put("begintime", begintime);
            map.put("endtime", endtime);
            map.put("status", Orders.COMPLETED);
            Integer getValidOrderCountList = ordersMapper.getNumberByStatusAndTime(map);
            getValidOrderCountList = getValidOrderCountList == null?0:getValidOrderCountList;
            validOrderCountList.add(getValidOrderCountList);


        });
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);
        HashMap map = new HashMap<>();
        map.put("endtime", endtime);
        Integer totalOrderCount = ordersMapper.getNumberByStatusAndTime(map);
        map.put("endtime", endtime);
        map.put("status", Orders.COMPLETED);
        Integer validOrderCount = ordersMapper.getNumberByStatusAndTime(map);
        Double orderCompletionRate = 0.0;
        if (totalOrderCount !=0.0)
            orderCompletionRate=(validOrderCount * 1.0 / totalOrderCount) ;

        return OrderReportVO
                .builder()
                .dateList(StringUtils.join(datelist,","))
                .orderCountList(StringUtils.join(orderCountList,","))
                .validOrderCountList(StringUtils.join(validOrderCountList,","))
                .totalOrderCount(totalOrderCount)
                .validOrderCount(validOrderCount)
                .orderCompletionRate(orderCompletionRate)
                .build();
    }

    @Override
    public SalesTop10ReportVO top10(LocalDate begin, LocalDate end) {
        List<String> nameList = new ArrayList<>();
        List<Integer> numberList = new ArrayList<>();

        LocalDateTime begintime = LocalDateTime.of(begin, LocalTime.MIN);
        LocalDateTime endtime = LocalDateTime.of(end, LocalTime.MAX);

        Map map = new HashMap<>();
        map.put("begintime", begintime);
        map.put("endtime", endtime);
        map.put("status",Orders.COMPLETED);
        List<GoodsSalesDTO> goodsSalesDTOList = ordersDetailMapper.getTop10(map);
        goodsSalesDTOList.forEach(list->{
            nameList.add(list.getName());
            numberList.add(list.getNumber());
        });
        return SalesTop10ReportVO
                .builder()
                .nameList(StringUtils.join(nameList,","))
                .numberList(StringUtils.join(numberList,","))
                .build();
    }

    @Override
    public void export(HttpServletResponse response) throws IOException {
        LocalDate begintime = LocalDate.now().minusDays(30);
        LocalDate endtime = LocalDate.now().plusDays(1);

        //查询概览数据
        BusinessDataVO businessDataVO = workSpaceService.getBusinessData(LocalDateTime.of(begintime,LocalTime.MIN),LocalDateTime.of(endtime,LocalTime.MAX));

        InputStream in = this.getClass().getClassLoader().getResourceAsStream("template/运营数据报表模板.xlsx");
        try {
            XSSFWorkbook excal = new XSSFWorkbook(in);
            XSSFSheet sheet = excal.getSheet("sheet1");
            sheet.getRow(1).getCell(1).setCellValue("时间："+begintime+endtime);
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());
            sheet.getRow(3).getCell(4).setCellValue(businessDataVO.getOrderCompletionRate());
            sheet.getRow(3).getCell(6).setCellValue(businessDataVO.getNewUsers());
            sheet.getRow(4).getCell(2).setCellValue(businessDataVO.getValidOrderCount());
            sheet.getRow(4).getCell(4).setCellValue(businessDataVO.getUnitPrice());
            sheet.getRow(3).getCell(2).setCellValue(businessDataVO.getTurnover());

            for (int i = 0;i<30;i++){
                LocalDate date = begintime.plusDays(i);
                BusinessDataVO businessDataVO2 = workSpaceService.getBusinessData(LocalDateTime.of(date,LocalTime.MIN),LocalDateTime.of(date,LocalTime.MAX));

                XSSFRow row = sheet.getRow(7 + i);
                row.getCell(1).setCellValue(date.toString());
                row.getCell(2).setCellValue(businessDataVO2.getTurnover());
                row.getCell(3).setCellValue(businessDataVO2.getValidOrderCount());
                row.getCell(4).setCellValue(businessDataVO2.getOrderCompletionRate());
                row.getCell(5).setCellValue(businessDataVO2.getUnitPrice());
                row.getCell(6).setCellValue(businessDataVO2.getNewUsers());


            }

            ServletOutputStream out = response.getOutputStream();
            excal.write(out);

            out.close();
            excal.close();

        } catch (IOException e) {
            e.printStackTrace();
        }



    }
}
